package de.mmis.core.tuplespace;

import java.io.IOException;

import org.apache.log4j.Logger;

import de.mmis.core.base.abstracttree.Tree;
import de.mmis.core.pojop.NetworkProxy;

/**
 * abstract class that can be used to implement information providing classes
 * using the {@link Tuplespace} and a {@link TuplespaceMultikeyMap} as the data
 * container
 * 
 * @author Christian Koch
 * 
 */
public abstract class TuplespaceInformationProvider {
	private final static Logger LOGGER = Logger
			.getLogger(TuplespaceInformationProvider.class);

	protected Tuplespace space;
	protected TuplespaceMultikeyMap map;

	private static final String MAP_NAME = "informationprovider";

	/**
	 * creates new information provider on specified Tuplespace
	 * 
	 * @param id
	 *            ID of the created {@link TuplespaceMultikeyMap}
	 * @param host
	 *            host name or IP of the {@link Tuplespace} to connect to
	 * @param port
	 *            port number of the {@link Tuplespace} to connect to
	 * @throws TuplespaceException
	 *             an error occurred while connecting or initializing data
	 *             container
	 */
	public TuplespaceInformationProvider(Tree id, String host, int port)
			throws TuplespaceException {
		try {
			space = NetworkProxy.createProxy(Tuplespace.class, host, port);
		} catch (IOException e) {
			throw new TuplespaceException("error while creating NetworkProxy",
					e);
		}

		map = new TuplespaceMultikeyMap(space, MAP_NAME, id);

		if (!map.isPresent()) {
			LOGGER.warn("WARNING: information provider map \"" + id
					+ "\" not found, generating new one");
			map.initMap();
		}
	}
}
